﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeTabling.DAI;
using TimeTabling.Core;
using System.Reflection;
using System.Data.SqlClient;
using System.Data;

namespace TimeTabling.DAL
{
    public class GenericDAO<T> : IGenericDAO<T>
    {
        private string connectionString;

        private string entityName;

        private IList<string> fieldsNames = new List<string>();

        public GenericDAO(string connectionString) {
            this.connectionString = connectionString;

            entityName = typeof(T).Name;

            //PropertyInfo[] propertyList = typeof(T).GetProperties();
            //foreach(var info in propertyList)
            //{
            //        fieldsNames.Add(info.Name);
            //}
            //Esto es lo mismo que lo comentado arriba pero con tipos Landa
            fieldsNames = typeof(T).GetProperties().Where(p=>p.GetType().IsPrimitive).Select(p => p.Name).ToList();
        }

        public void Add(T entity)
        {
           
            string command = string.Format("Insert into {0} Values({1})",entityName, string.Join(",",fieldsNames));
           
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                SqlCommand sqlCommand = new SqlCommand(command, sqlConnection);
                foreach (var field in fieldsNames)
                {
                    sqlCommand.Parameters.Add(string.Format("@{0}",field), typeof(T).GetProperty(field).GetValue(entity,null));
                }
                try
                {
                    sqlConnection.Open();
                    sqlCommand.ExecuteNonQuery();
                }
                finally
                {
                    if (sqlConnection.State != ConnectionState.Closed)
                    {
                        sqlConnection.Close();
                    }
                }
            }
        }
    }
}
